﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

public class ResourceManager : MonoBehaviour
{
	private static ResourceManager instance = null;

	public static ResourceManager Inst
	{
		get
		{
			if (instance == null)
			{
				GameObject manager = new GameObject("_ResourceManager", typeof(ResourceManager));

				GameObject.DontDestroyOnLoad(manager);

				instance = manager.GetComponent<ResourceManager>();
			}

			return instance;
		}
	}

	public void PatchDataFile(System.Action onComplete)
	{
		StartCoroutine(PatchDataFile("", onComplete));
	}

	public IEnumerator PatchDataFile(object dummy, System.Action onComplete)
	{
		WWW versionFile = new WWW(Settings.Instance.DataUrl + "ver.txt");

		yield return versionFile;

        Debug.Log("Local:" + Application.persistentDataPath);
        Debug.Log(versionFile.text);

		string[] versionInfoList = versionFile.text.Split('\n');
		Dictionary<string, WWW> resultList = new Dictionary<string, WWW>();

		foreach (string versionInfo in versionInfoList)
		{
            string verInfo = versionInfo.Trim();
			if (verInfo.Length <= 0)
				continue;//TODO:에러처리
			string[] data = verInfo.Split(':');
            if (data.Length < 3)
                continue;//TODO:에러처리
			string fileName = data[0];
			int clientVerion = PlayerPrefs.GetInt(fileName, int.MinValue);
			int serverVersion;
			if (!int.TryParse(data[1], out serverVersion))
				continue;
            string cliFilePath = Application.persistentDataPath + "/" + fileName;
            if (clientVerion != serverVersion || !File.Exists(cliFilePath))
			{
				//Debug.Log(fileName);
				resultList.Add(verInfo, new WWW(Settings.Instance.DataUrl + fileName));
			}
            else
            {
                //140808 hikim - compare file checksum
                string fileCSSvr = data[2];
                string fileCS = SHA.Instance.ComputeFileHashToBase64(cliFilePath);
                if (fileCS != fileCSSvr)
                {
                    //Debug.Log(fileName);
                    resultList.Add(verInfo, new WWW(Settings.Instance.DataUrl + fileName));
                }
            }
		}

		while (true)
		{
			bool completeState = true;

			foreach (var result in resultList)
			{
				if (!result.Value.isDone)
				{
					completeState = false;

					break;
				}
			}

			if (completeState)
				break;

			yield return null;
		}

		foreach (var result in resultList)
		{
			string[] data = result.Key.Split(':');
			string fileName = data[0];
			int clientVerion = PlayerPrefs.GetInt(fileName, int.MinValue);
			int serverVersion = int.Parse(data[1]);

			Debug.Log(string.Format("'{0}' update version : {1}", fileName, serverVersion));

			PlayerPrefs.SetInt(fileName, serverVersion);

            Debug.Log(Application.persistentDataPath + "/" + fileName);
            //var file = System.IO.File.Open(Application.persistentDataPath + "/" + fileName, System.IO.FileMode.OpenOrCreate);
            //var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            //bf.Serialize(file, result.Value.text);
            //File.WriteAllBytes(Application.persistentDataPath + "/" + fileName, result.Value.bytes);
            using (FileStream fs = File.OpenWrite(Application.persistentDataPath + "/" + fileName))
            {
                fs.Write(result.Value.bytes, 0, result.Value.bytes.Length);
            }

			//file.Close();
		}

		onComplete();
	}

	/// <summary>
	/// 플레이어 choice member 4명 모델 오브젝트를 파괴하지않고 계속 유지한다.
	/// </summary>
	Dictionary<int, GameObject> choiceMemberGoDic = new Dictionary<int, GameObject>();
	public GameObject GetChoiceMemberGo(int _no)
	{
		if(_no==0)
			return null;
		if(choiceMemberGoDic.ContainsKey(_no) )
		{
			Debug.LogError("GetChoiceMemberGo  exist return "+_no);
			choiceMemberGoDic[_no].SetActive(true);
			return choiceMemberGoDic[_no];
		}
		else {
			Debug.LogError("GetChoiceMemberGo  dont exist no= "+_no);
			return null;
		}
	}

	public bool IsChoiceMemberGo(GameObject go)
	{
		foreach( var pair in choiceMemberGoDic) {
			if(pair.Value == go)
				return true;
		}
		return false;
	}

	public void AddChoiceMemberGo(int no, GameObject go)
	{
		choiceMemberGoDic.Add ( no, go);
		go.GetComponent<Animation>().playAutomatically = false;
		Debug.LogError("AddChoiceMemberGo  "+no+ "    dicCount="+choiceMemberGoDic.Count);
	}

	// 멤버 교체한 경우 제거//
	public void RemoveChoiceModel(GameObject go)
	{
		int keyToDelete = -1;
		foreach( var pair in choiceMemberGoDic) {
			if(pair.Value == go) {
				keyToDelete = pair.Key;
				break;
			}
		}
		if(keyToDelete!=-1) {
			choiceMemberGoDic.Remove(keyToDelete);
			Debug.LogError("RemoveChoiceModel  mid="+keyToDelete+"   dicCount="+choiceMemberGoDic.Count);
		}
	}

	public void ClearAllChoiceModel()
	{
		foreach( var pair in choiceMemberGoDic) {
			Destroy(pair.Value);
		}
		choiceMemberGoDic.Clear();
	}

	public void RetainChoiceMemberGo()
	{
		foreach( var pair in choiceMemberGoDic) {
			pair.Value.transform.parent = gameObject.transform;
			pair.Value.SetActive(false);
		}
	}

	public void ClearChoiceMemberComponents()
	{
		foreach( var pair in choiceMemberGoDic) {
			GameObject go = pair.Value;
			BattleManager.ClearBattlePawnComponent(go);
		}
	}
	
}
